﻿Ext.data.XmlReader = Ext.extend(Ext.data.Reader, {




    createAccessor: function () {
        var selectValue = function (key, root, defaultValue) {
            var node = Ext.DomQuery.selectNode(key, root),
                val;
            if (node && node.firstChild) {
                val = node.firstChild.nodeValue;
            }
            return Ext.isEmpty(val) ? defaultValue : val;
        };

        return function (key) {
            var fn;

            if (key == this.totalProperty) {
                fn = function (root, defaultValue) {
                    var value = selectValue(key, root, defaultValue);
                    return parseFloat(value);
                };
            }

            else if (key == this.successProperty) {
                fn = function (root, defaultValue) {
                    var value = selectValue(key, root, true);
                    return (value !== false && value !== 'false');
                };
            }

            else {
                fn = function (root, defaultValue) {
                    return selectValue(key, root, defaultValue);
                };
            }

            return fn;
        };
    } (),


    getResponseData: function (response) {
        var xml = response.responseXML;

        if (!xml) {
            throw { message: 'Ext.data.XmlReader.read: XML data not found' };
        }

        return xml;
    },

    //转换数据
    getData: function (data) {
        return data.documentElement || data;
    },

    //获取this.root表示的数据
    getRoot: function (data) {
        var nodeName = data.nodeName,
            root = this.root;

        if (!root || (nodeName && nodeName == root)) {
            return data;
        } else {
            return Ext.DomQuery.selectNode(root, data);
        }
    },












    constructor: function (config) {
        config = config || {};




        Ext.applyIf(config, {
            idProperty: config.idPath || config.id,
            successProperty: config.success
        });

        Ext.data.XmlReader.superclass.constructor.call(this, config);
    },


    extractData: function (root, returnRecords) {
        var recordName = this.record;

        if (recordName != root.nodeName) {
            root = Ext.DomQuery.select(recordName, root);
        } else {
            root = [root];
        }

        return Ext.data.XmlReader.superclass.extractData.call(this, root, returnRecords);
    },


    getAssociatedDataRoot: function (data, associationName) {
        return Ext.DomQuery.select(associationName, data)[0];
    },


    readRecords: function (doc) {

        if (Ext.isArray(doc)) {
            doc = doc[0];
        }


        this.xmlData = doc;

        return Ext.data.XmlReader.superclass.readRecords.call(this, doc);
    }
});

Ext.data.ReaderMgr.registerType('xml', Ext.data.XmlReader);